package ua.epam.classloaderlab;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Util {

	public Util() {
	}

	public static String concatenate(String... args) {
		StringBuilder sb = new StringBuilder();
		for (String arg : args)
			sb.append(arg);
		return sb.toString();
	}

	public static byte[] load(File file) throws IOException {
		InputStream stream = new FileInputStream(file);
		byte buff[] = new byte[stream.available()];
		DataInputStream in = new DataInputStream(stream);
		in.readFully(buff);
		in.close();
		return buff;
	}

	public static void compile(String filename, File directory) {
		String command = concatenate("javac -d ", directory.getAbsolutePath(), " ", filename);
		runProcess(command, directory);
	}

	private static RuntimeException createException(InputStream ins) throws Exception {
		StringBuilder msg = new StringBuilder();
		BufferedReader in = new BufferedReader(new InputStreamReader(ins));
		for (String line = in.readLine(); line != null; line = in.readLine())
			msg.append(line).append("\n");
		return msg.length() == 0 ? null : new RuntimeException(msg.toString());

	}

	private static void runProcess(String command, File directory) {
		RuntimeException exception = null;
		Process process = null;
		try {
			process = Runtime.getRuntime().exec(command);
			exception = createException(process.getErrorStream());
			process.waitFor();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		if (exception != null)
			throw exception;
		if (process.exitValue() != 0)
			throw new RuntimeException("Bad exit value");
	}

}
